package com.platform.destiny.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import com.platform.destiny.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.DenyAllPermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

/**
 * https://www.imooc.com/article/326405
 * 用户鉴权
 *
 * @Description
 * @Author kaiyang
 * @Date 2024-02-01 2:19 PM
 */
@Slf4j
@Component
public class AppPermissionEvaluator extends DenyAllPermissionEvaluator implements PermissionEvaluator {

    AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(Authentication auth, Object obj, Object permission) {
        log.info("obj {} permission {}", obj, permission);
        UserDto dto = (UserDto) auth.getPrincipal();
        List<String> permissions = dto.getPermissions();
        return CollUtil.contains(permissions, String.valueOf(permission));

    }

    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        log.info("targetId {} targetType {} permission {}", targetId, targetType, permission);
        UserDto dto = (UserDto) auth.getPrincipal();
        List<String> permissions = dto.getPermissions();
        return CollUtil.contains(permissions, String.valueOf(permission));
    }


}
